import urllib2
import urllib
import xml.etree.ElementTree as xmlParser
from content.contprov.general_classes import OneLink, clean_text

def ask_wikipedia(keywords):
	links = []
	url = 'http://en.wikipedia.org/w/api.php?action=opensearch&format=xml&search='
	th = []
	for k in keywords:
		keyword = k.keyword
		keyword = keyword.replace(" ", "+")
		fulurl = url+keyword
		response = urllib2.urlopen(fulurl)
		the_page = response.read()
		someSh = "{http://opensearch.org/searchsuggest2}"
		dom = xmlParser.fromstring(the_page).find(someSh+"Section").findall(someSh+"Item")
		#print list(dom)
		for e in dom:
			linkUrl = e.find(someSh+"Url").text
			linkDescription = e.find(someSh+"Description").text
			duck = OneLink(url=linkUrl, description=clean_text(linkDescription))
			links.append(duck)
	return links

def ask_once_wikipedia(url, place):
	links = []
	response = urllib2.urlopen(url)
	the_page = response.read()
	someSh = "{http://opensearch.org/searchsuggest2}"
	dom = xmlParser.fromstring(the_page).find(someSh+"Section").findall(someSh+"Item")
	#print list(dom)
	for e in dom:
		linkUrl = e.find(someSh+"Url").text
		linkDescription = e.find(someSh+"Description").text
		duck = OneLink(url=linkUrl, description=clean_text(linkDescription))
		links.append(duck)
